﻿using AbpApplication.Expand;
using AbpApplication.InPut;
using AbpEntityFrameworkcore.DbContext;
using AbpToDomain.EntityInfo;
using AbpToDomain.View;
using Azure;
using JetBrains.Annotations;
using LinqSharp;
using Mesosphere.Dto;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using wms_wpf.Apiservice;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace AbpApplication.AppServices
{
    public class ViewService : ApplicationService, IViewService
    {


        private readonly MyDbContext context;
        private readonly IRepository<Box> Box_res;
         private readonly IRepository<BoxGrid> BoxGrid_res;
        private readonly  IRepository<Warehouse> Warehouse_res;
        private readonly IRepository<PutInOrder> PutInOrder_res;
        private readonly IRepository<PutOutOrder> PutOutOrder_res;
        private readonly IRepository<NeetOutMaterial> NeetOutMaterial_res;
        private readonly IRepository<SowingWallLine> SowingWallLine_res;

        private readonly ILoginHelper loginHelper;
        private readonly QueryDynamic queryDynamic;
        public ViewService(MyDbContext context,
            IRepository<Box> box_res,
            IRepository<BoxGrid> boxGrid_res,
            IRepository<Warehouse> warehouse_res,
            ILoginHelper loginHelper,
            QueryDynamic queryDynamic,
            IRepository<PutInOrder> putInOrder_res,
            IRepository<PutOutOrder> putOutOrder_res,
            IRepository<NeetOutMaterial> neetOutMaterial_res,
            IRepository<SowingWallLine> sowingWallLine_res)
        {
            this.context = context;
            Box_res = box_res;
            BoxGrid_res = boxGrid_res;
            Warehouse_res = warehouse_res;
            this.loginHelper = loginHelper;
            this.queryDynamic = queryDynamic;
            PutInOrder_res = putInOrder_res;
            PutOutOrder_res = putOutOrder_res;
            NeetOutMaterial_res = neetOutMaterial_res;
            SowingWallLine_res = sowingWallLine_res;
        }





        public async Task<ApiResponsePage> View_Box_WarehouseLine(InPut_ViewService6 InPut)
        {
            List<View_Box_WarehouseLine> data=  queryDynamic.QueryDynameicView_Box_WarehouseLine(InPut.BoxCode, InPut.WarehouseLineCode);
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);
        }   
        public async Task<ApiResponsePage> View_LogNote(InPut_ViewService7 InPut)
        {
           List<lognote> data=queryDynamic.QueryDynameicView_View_Lognote(InPut.Type,InPut.StartTime,InPut.EndTime,InPut.Note,
               InPut.User,InPut.Definition,InPut.MaterialCode,InPut.MaterialName,InPut.Batch,InPut.Size,InPut.OrderNo,InPut.BoxCode,InPut.WarehouseLineCode);
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);
        }
        public async Task<ApiResponsePage> View_MaterialProperty(InPut_ViewService8 InPut)
        {
            List<MaterialProperty> data=   queryDynamic.QueryDynameic_MaterialProperty(InPut.MaterialProertyname, InPut.Type, InPut.Description);
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);
        }
        //已用
        public async Task<ApiResponse> View_WareHouse()
        {
            try
            {
                List<Warehouse> warehouses = await Warehouse_res.GetListAsync();
                return new ApiResponse("获取成功", true, warehouses);
            }
            catch (Exception ex)
            {
                Logger.LogError("View_WareHouse错误");
                return new ApiResponse("View_WareHouse错误", false, null);
            }
        }
        public async Task<ApiResponsePage> View_Box(InPut_ViewService InPut)
        {
            try
            {
                IQueryable<View_Box> view_Boxequery = context.viewBox;
                if (!string.IsNullOrEmpty(InPut.BoxCode))
                {
                    view_Boxequery = view_Boxequery.Where(x => x.BoxCode.Contains(InPut.BoxCode));
                }
                List<View_Box> view_Boxes = view_Boxequery.ToList();
                long count = view_Boxes.LongCount();//计算出了总条数
                long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
                view_Boxes = view_Boxes.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
                return new ApiResponsePage("获取成功", true, view_Boxes, count, pageCount);
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(InPut, " View_Box");
                return new ApiResponsePage("View_Box错误", false, null, null, null);
            }
        }
        public async Task<ApiResponsePage> View_BoxGrid_Material(InPut_ViewService2 InPut)
        {
            var boxgrids = await BoxGrid_res.WithDetailsAsync();
            if (!string.IsNullOrEmpty(InPut.BoxCode))
            {
                boxgrids = boxgrids.Where(x => x.TheBox.BoxCode == InPut.BoxCode);
            }
            long count = boxgrids.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            var res = boxgrids.Select
                (x => new {
                    BoxGridCode = x.BoxGridCode,
                    CreateTime = x.TheBox.CreateTime,
                    UpdateTime = x.TheBox.UpdateTime,
                    BoxPositionQuantity=x.BoxPositionQuantity

                });
            res = res.SelectPage(InPut.PageIndex, InPut.PageSize);
            return new ApiResponsePage("获取成功", true, res.ToList(), count, pageCount);
        }
        public async Task<ApiResponsePage> View_WareHouseLine(InPut_ViewService3 InPut)
        {
            List<WarehouseLine> data = queryDynamic.QueryDynameic(InPut.Xaxis, InPut.Yaxis, InPut.Zaxis, InPut.Id_Warehouse);
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);
        }
        public async Task<ApiResponsePage> View_TaskOrder(InPut_ViewService5 InPut)
        {
            List<View_TaskOrder> data = queryDynamic.QueryDynameicView_TaskOder(InPut.Type, InPut.OrderNo, InPut.BoxCode, InPut.State,
                                                     InPut.WarehouseCode, InPut.InlethouseCode, InPut.TaskOrderCode,
                                                     InPut.groupPriority, InPut.taskPriority, InPut.Machine);
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);
        }
        public async Task<ApiResponsePage> View_Material_WarehouseLine(InPut_ViewService9 inPut)
        {
            List<View_Material_WarehouseLine> data = queryDynamic.QueryDynameicView_Material_WarehouseLine( inPut.BoxPositionCode, inPut.MaterialCode,inPut.WarehouseLineCode,
                inPut.State,inPut.Type, inPut.PutInDate);
            data = data.OrderBy(x => x.CreatedDate).ToList();
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / inPut.PageSize);
            data = data.SelectPage(inPut.PageIndex, inPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);
        }
        public async Task<ApiResponse> View_Inlethouse(string? InlethouseCode)
        {
          List<InlethouseLine> inlethouseLines=   await context.inlethousesLine.Include(x=>x.Box).ToListAsync();
            if (!string.IsNullOrWhiteSpace(InlethouseCode))
            {
                inlethouseLines=inlethouseLines.Where(x=>x.InlethouseLineCode.Contains(InlethouseCode)).ToList();
            }

            inlethouseLines = inlethouseLines.GroupBy(x=>x.InlethouseLineCode.Substring(x.InlethouseLineCode.Length-1)).
          OrderByDescending(group=>group.Key).Select(group => group
                .OrderBy(x=>x.InlethouseLineCode.Substring(x.InlethouseLineCode.Length-8))  
                .ToList())
            .SelectMany(group => group) // 展开分组  
            .ToList();


            var inlethouselineDto=       inlethouseLines.Select(x => new {x.Box?.BoxCode , x.InlethouseLineCode,x.IsOccupy}).Take(8). ToList();
            return new ApiResponse("获取成功",true, inlethouselineDto);

        }//缓存区图形
        public async Task<ApiResponsePage> View_Material(InPut_ViewService4 InPut)
        {
            List<View_Material> data = queryDynamic.QueryDynameicView_Material(InPut.BoxPositionCode);
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);

        }
        public async Task<ApiResponsePage> View_NeetOutMaterial(InPut_ViewService10 InPut)
        {
            List<View_NeetOutMaterial> data = queryDynamic.QueryDynameicView_View_NeetOutMaterial(InPut.BoxCode,InPut.Machine);
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);
        }
        public async Task<ApiResponse> View_InlethouseLine()
        {
            List<InlethouseLine> inlethouseLines= await   context.inlethousesLine.ToListAsync();
            return new ApiResponse("获取成功",true, inlethouseLines);
        }
        public async Task<ApiResponsePage> View_PutInOrder(InPut_ViewService11 InPut)
        {
            List<PutInOrder> data = await context.putInOrder.WhereIf(!string.IsNullOrEmpty(InPut.Symbol), x => x.Symbol.Contains(InPut.Symbol))
                                 .WhereIf(!string.IsNullOrEmpty(InPut.MaterialCode), x => x.MaterialCode.Contains(InPut.MaterialCode))
                                 .WhereIf(!string.IsNullOrEmpty(InPut.Batch), x => x.Batch.Contains(InPut.Batch))
                                 .WhereIf(!string.IsNullOrEmpty(InPut.Consumer_MaterialId), x => x.Consumer_MaterialId.Contains(InPut.Consumer_MaterialId))
                                 .WhereIf(!string.IsNullOrEmpty(InPut.State), x => x.State == InPut.State)
                                 .WhereIf(!string.IsNullOrEmpty(InPut.Quantity.ToString()), x => x.Quantity == InPut.Quantity).ToListAsync();

            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);

        }
        public async Task<ApiResponsePage> View_PutOutOrder(InPut_ViewService12 InPut)
        {
           List<PutOutOrder> data  =  await context.putOutOrder.WhereIf(!string.IsNullOrEmpty(InPut.Symbol),x=>x.Symbol.Contains(InPut.Symbol)).
                WhereIf(!string.IsNullOrEmpty(InPut.Batch), x => x.Symbol.Contains(InPut.Batch)).
                WhereIf(!string.IsNullOrEmpty(InPut.State), x => x.State.Contains(InPut.State)).ToListAsync();
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();

         var putOutOrderDtos = data
         .GroupBy(order => order.Symbol) // 按照 Symbol 分组
         .Select(group => new PutOutOrderDto2
         {
             Symbol = group.Key, // 获取分组的 Key
             PutOutOrders = group.ToList() 
             // 将分组的订单转换为列表
         })
         .ToList();
            return new ApiResponsePage("获取成功", true, putOutOrderDtos, count, pageCount);
        }
        public async Task<ApiResponse> View_Guid_NeetOutMaterial(string Symbol)
        {
           List<NeetOutMaterial> neetOutMaterials=   await NeetOutMaterial_res.GetListAsync(x => x.OrderNo == Symbol);
           List<View_NeetOutMaterial> view_NeetOutMaterials= await  context.View_NeetOutMaterials.ToListAsync();
           view_NeetOutMaterials = view_NeetOutMaterials.Where(x => neetOutMaterials.Any(y => y.Id_NeetOutMaterial == x.Id_NeetOutMaterial)).ToList();
           return new ApiResponse("获取成功", true, view_NeetOutMaterials);
        }
        public async Task<ApiResponse> View_SowingWallLine(string Machine)
        {
             List<SowingWallLine> sowingWallLines= await SowingWallLine_res.GetListAsync(x=>x.Mchine==Machine);
            sowingWallLines = sowingWallLines.OrderBy(x => x.SowingWallLine_Name.Substring(x.SowingWallLine_Name.Length - 1)).
                                             OrderBy(x => x.SowingWallLine_Name.Substring(x.SowingWallLine_Name.Length - 3)).
                                           OrderBy(x => x.SowingWallLine_Name.Substring(x.SowingWallLine_Name.Length - 5)).ToList();
            return new ApiResponse("获取成功", true, sowingWallLines);
        }
        public async Task<ApiResponse> View_PutOutOrder2(InPut_ViewService13 InPut)
        {

            var data = await context.putOutOrder. WhereIf(!string.IsNullOrEmpty(InPut.Symbol),x=>x.Symbol.Contains( InPut.Symbol)).
                                                  WhereIf(!string.IsNullOrEmpty(InPut.MaterialCode),x=>x.MaterialCode .Contains( InPut.MaterialCode)). Where(x => x.IsFinish == InPut.IsFinish).ToListAsync();
            return new ApiResponse("获取成功", true, data);
        }
        public async Task<ApiResponsePage> View_BoxProportion(InPut_ViewService14 InPut)//空料比
        {

            // 统一构建基础查询
            IQueryable<Box> baseQuery = context.boxs.AsQueryable();

            // 处理 BoxGridQuantity 过滤条件
            if (InPut.BoxGridQuantity != 0) // 假设 BoxGridQuantity 是 int 类型
            {
                baseQuery = baseQuery.Where(x => x.BoxGridQuantity == InPut.BoxGridQuantity);
            }

            // 根据 Empty 状态添加不同条件
            if (InPut.Empty)
            {
                // 优化为不存在任何 MaterialBase 的记录
                baseQuery = baseQuery.Where(x => !x.BoxGrids.Any(bg =>
                    bg.BoxPositions.Any(bp => bp.MaterialBase != null))).Select(x => new Box
                    {
                        BoxCode = x.BoxCode,
                        BoxGridQuantity = x.BoxGridQuantity,
                        BoxGrids = x.BoxGrids.Select(bg => new BoxGrid
                        {
                            BoxPositions = bg.BoxPositions.Select(bp => new BoxPosition
                            {
                                MaterialBase = bp.MaterialBase
                            }).ToList()
                        }).ToList()
                    });
            }
            else
            {
                baseQuery = baseQuery
                    .Where(x => x.WarehouseLine != null)
                    // 使用投影替代 Include
                    .Select(x => new Box
                    {
                        BoxCode = x.BoxCode,
                        BoxGridQuantity = x.BoxGridQuantity,
                        BoxGrids = x.BoxGrids.Select(bg => new BoxGrid
                        {
                            BoxPositions = bg.BoxPositions.Select(bp => new BoxPosition
                            {
                                MaterialBase = bp.MaterialBase
                            }).ToList()
                        }).ToList()
                    });
                
            }

            // 执行查询
            var boxes = await baseQuery.ToListAsync();

            // 内存中处理投影
            var data = boxes.Select(box => new
            {
                BoxCode = box.BoxCode,
                BoxGridQuantity = box.BoxGridQuantity,
                // 优化计数逻辑
                EmptyMaterialRatio = box.BoxGrids
                    .Count(bg => bg.BoxPositions.All(bp => bp.MaterialBase == null))
                    + "/" + box.BoxGridQuantity
            }).ToList();
            if (InPut.EmptyGrid)
            {
                data = data.Where(x => !x.EmptyMaterialRatio.StartsWith("0")).ToList();
            }

            data = data.OrderBy(x=>x.EmptyMaterialRatio).ToList();
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);
        }
        public async Task<ApiResponse> HML_GetMostMaterial()
        {
         var data=  context.materialBases.GroupBy(x => x.MaterialCode)
           .Select(group => new
           {
               MaterialCode = group.Key,
               MaxCount = group.Count(),
           })
           .OrderByDescending(x => x.MaxCount)
           .Take(10);
            return new ApiResponse("获取成功", true, data);
        }
        public async Task<ApiResponse> HML_GetEveryDayMaterial()
        {
            var dataModel = context.materialBases.Where(x => x.CreatedDate >= DateTime.Now.AddDays(-10)
            && x.CreatedDate <= DateTime.Now).GroupBy(x => x.CreatedDate.Date).
                Select(x => new
                {
                    Day =x.Key.ToShortDateString(),
                    Count = x.Count(),
                });

            var dataTuple = new
            {
                data = dataModel,
                Name="小件仓",
            };
        
            var data = new
            {
                title = "入库趋势",
                data = dataTuple,
                Base=dataTuple.data.ToList(). Sum(x=>x.Count),//这里语法什么错误
                Unit="件",
            };
             
            return new ApiResponse("获取成功", true, data);
        }
        public async Task<ApiResponse> HML_GetlogNote()
        {
            var dataModel = context.lognotes.GroupBy(x => x.Type).Select(x => new
            {
                Type = x.Key,
                Count = x.Count(),
            });
            return new ApiResponse("获取成功", true, dataModel);
        }
        public async Task<ApiResponsePage> View_CoutomerCheckList(InPut_ViewService15 InPut)
        {
            List<CustomCheckList> data = await context.customCheckLists.Where(x=>x.IsCheck==false&&x.IsExist==InPut.IsExist).ToListAsync();
            long count = data.LongCount();//计算出了总条数
            long pageCount = (long)Math.Ceiling(count * 1.0 / InPut.PageSize);
            data = data.SelectPage(InPut.PageIndex, InPut.PageSize).ToList();
            return new ApiResponsePage("获取成功", true, data, count, pageCount);
        }
    }
}
